package com.yonyou.openapi.service;

import com.yonyou.openapi.base.exception.BusinessException;
import com.yonyou.openapi.base.sso.sso.SingleSignOn;
import com.yonyou.openapi.base.utils.HttpUtils;
import org.springframework.stereotype.Component;

/**
 * @author nishch
 * @description: 单点登录至YS首页
 * @date 2023/7/26
 */
@Component
public class SSOToYSIndexService extends SingleSignOn {


    /**
     * 单点登录凭证列表页面
     * @param userId 三方用户唯一标识
     * @return 最终单点登录地址
     */
    public String index(String userId){
        return getSSOUrlToIndex(init(userId));
    }

    public String getRedirectUrl(String usercode, String type) {
        String ip;
        if ("pro".equals(type)) {
            ip = properties.getNcZsUrl();
        } else {
            ip = properties.getNcCsUrl();
        }
        String token = getToken(usercode, type);
        return ip + "nccloud/resources/uap/rbac/thirdpartylogin/main/index.html?accesstoken=" + token + "&redirect_uri=";
    }

    private String getToken(String usercode, String type) {
        String ip;
        String dsname;
        if ("pro".equals(type)) {
            ip = properties.getNcZsUrl();
            dsname = properties.getNcZsDsname();
        } else if ("test".equals(type)) {
            ip = properties.getNcCsUrl();
            dsname = properties.getNcCsDsname();
        } else {
            throw new BusinessException("type类型不正确，应为正式pro或测试test");
        }
        String client_id = properties.getClientId();
        String busicentercode = properties.getBusicentercode();
        String url = ip + "service/genThirdPartyAccessToken?dsname=" + dsname + "&usercode=" + usercode + "&client_id=" + client_id + "&busicentercode=" + busicentercode;
        String token = HttpUtils.doGet(url);
        if (token.isEmpty()) {
            throw new BusinessException("单点登录异常，请检查参数配置以及白名单配置");
        }
        return token;
    }
}
